﻿using Bnbjoy.Domain.Abstract;
using Bnbjoy.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bnbjoy.Domain.Concrete
{
    public class ClientRepository : IClientRepository
    {

        public async Task<Client> FindById(string Id)
        {
            try
            {
                using (BnbjoyBackendDbEntities bnbjoyBackendDbEntities = new BnbjoyBackendDbEntities())
                {
                    return await bnbjoyBackendDbEntities.Clients.AsNoTracking().Where(x => x.Id == Id).FirstOrDefaultAsync();
                }
            }
            catch (Exception ex) 
            {
                return null;
            }
        }

        public async Task<Client> FirstClient()
        {
            using (BnbjoyBackendDbEntities bnbjoyBackendDbEntities = new BnbjoyBackendDbEntities())
            {
                return await bnbjoyBackendDbEntities.Clients.AsNoTracking().FirstOrDefaultAsync();
            }
        }

        public async Task<Client> InsertClient(Client client)
        {
            using (BnbjoyBackendDbEntities bnbjoyBackendDbEntities = new BnbjoyBackendDbEntities())
            {
                var existedClient = await FindById(client.Id);
                if (existedClient == null)
                {
                    bnbjoyBackendDbEntities.Clients.Add(client);
                    await bnbjoyBackendDbEntities.SaveChangesAsync();
                    return client;
                }
                else
                {
                    return null;
                }
            }
        }

        public async Task<IEnumerable<Client>> InsertClients(IEnumerable<Client> clients)
        {
            List<Client> tempClients = new List<Client>(); //临时存放可被添加的clients

            using (BnbjoyBackendDbEntities bnbjoyBackendDbEntities = new BnbjoyBackendDbEntities())
            {
                foreach (var client in clients)
                {
                    var existedClient = await FindById(client.Id);
                    if (existedClient == null)
                        tempClients.Add(client);
                }

                if (tempClients.Count > 0)
                {
                    bnbjoyBackendDbEntities.Clients.AddRange(tempClients);
                    await bnbjoyBackendDbEntities.SaveChangesAsync();
                }

                return tempClients;
            }
        }
    }
}
